<?php


//验证验证码
function check_captcha($input_captcha)
{
    if ($input_captcha) {
        $seccode = session('seccode');
        if (strtoupper($input_captcha) == $seccode) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

//生成验证码
function generate_captcha()
{
    ob_clean();
    $seccode = makeSeccode();
    $code = new \App\Support\seccode();
    $code->code = $seccode;
    $code->width = 90;
    $code->height = 26;
    $code->background = 1;
    $code->adulterate = 1;
    $code->scatter = '';
    $code->color = 1;
    $code->size = 0;
    $code->shadow = 1;
    $code->animator = 0;
    $code->datapath = 'seccode/';
    return response($code->display())->header('Content-Type', 'image/jpeg');
}

function makeSeccode()
{
    $seccode = random(6, 1);
    $seccodeunits = '';

    $s = sprintf('%04s', base_convert($seccode, 10, 23));
    $seccodeunits = 'ABCEFGHJKMPRTVXY2346789';
    if ($seccodeunits) {
        $seccode = '';
        for ($i = 0; $i < 4; $i++) {
            $unit = ord($s{$i});
            $seccode .= ($unit >= 0x30 && $unit <= 0x39) ? $seccodeunits[$unit - 0x30] : $seccodeunits[$unit - 0x57];
        }
    }
    session(['seccode' => $seccode]);
    return $seccode;
}

function random($length, $numeric = 0)
{
    $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
    $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
    $hash = '';
    $max = strlen($seed) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $seed{mt_rand(0, $max)};
    }
    return $hash;
}

//trim单个或数组中的字符串
function trim_fileds($inputs)
{
    $params = '';
    if (is_array($inputs)) {
        foreach ($inputs as $k => $v) {
            $params[$k] = trim($v);
        }
    } else {
        $params = trim($inputs);
    }
    return $params;
}

/*闪存重定向
 * $url       重定向地址
 *$message    提示信息
 *$type       提示类别，1不带原始提交的参数，2携带原始提交的参数
 * 跳转的页面用session接收传递的参数message
 */
function show_message($url, $message, $type = 1)
{
    if ($type == 2) {
        return redirect($url)->with('message', $message)->withInput();
    } else {
        return redirect($url)->with('message', $message);
    }
}


function getRandNum($length = 6)
{
    $key = '';
    $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
    for ($i = 0; $i < $length; $i++) {
        $key .= $pattern{mt_rand(0, 35)};    //生成php随机数
    }
    return $key;
}

//重新加密
function setMd5ByMark($password, $mark = '')
{
    return md5(md5($password) . $mark);

}

/*替换集合中某字段的值为另一集合中的值
 *$collection       被替换集合
 *$textArr    目标集合
 *$name       被替换集合中的字段名
 *$replaceName       目标集合中字段名
 */
function replace_field($collection, $textArr, $name, $replaceName)
{
    foreach ($collection as $col) {
        foreach ($textArr as $text) {
            if ($col->$name == $text->$name) {
                $col->$name = $text->$replaceName;
            }
        }
    }
}


if (!function_exists('msubstr')) {
    /**
     * 字符截取,支持中英文
     *
     * @param $str
     * @param int $start
     * @param $length
     * @param string $charset
     * @param bool|true $suffix
     * @return string
     * author zl
     */
    function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
    {
        if (function_exists("mb_substr"))
            return mb_substr($str, $start, $length, $charset);
        elseif (function_exists('iconv_substr')) {
            return iconv_substr($str, $start, $length, $charset);
        }
        $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("", array_slice($match[0], $start, $length));
        if ($suffix) return $slice . "…";
        return $slice;
    }
}


function childTree($res, $myid, $mid, $pid, $level = 0)
{
    static $childs = array();
    foreach ($res as $k => $v) {
        if ($v[$pid] == $myid) {
            $v['prefix'] = $level ? str_repeat('&nbsp;', $level * 4) . '∟&nbsp;' : str_repeat('&nbsp;', $level * 4);
            $childs[] = $v;
            childTree($res, $v[$mid], $mid, $pid, $level + 1);
        }
    }
    return $childs;

}

/** 二维数组无限级分类(找下级)  BY ZJC
 * Array    $m     需要递归查询的结果集
 * String   $name      需要查询下级从属的ID
 * Int      $pid     数据库中ID的字段名
 * return Array   返回循环查找后的二维数组结果
 */
function levelTree($res, $idField, $pidField, $pid = 0)
{
    $arr = array();
    if (empty($res)) {
        return $arr;
    }
    foreach ($res as $v) {
        if ($v[$pidField] == $pid) {
            $v['child'] = levelTree($res, $idField, $pidField, $v[$idField]);
            $arr[] = $v;
        }
    }
    return $arr;
}

//对二维数组进行某个字段的升序排列
function sortArrayAsc($preData, $sortType = 'sort')
{
    $sortData = array();
    foreach ($preData as $key_i => $value_i) {
        $sort_i = $value_i[$sortType];
        $min_key = '';
        $sort_total = count($sortData);
        foreach ($sortData as $key_j => $value_j) {
            if ($sort_i < $value_j[$sortType]) {
                $min_key = $key_j + 1;
                break;
            }
        }
        if (empty($min_key)) {
            array_push($sortData, $value_i);
        } else {
            $sortData1 = array_slice($sortData, 0, $min_key - 1);
            array_push($sortData1, $value_i);
            if (($min_key - 1) < $sort_total) {
                $sortData2 = array_slice($sortData, $min_key - 1);
                foreach ($sortData2 as $value) {
                    array_push($sortData1, $value);
                }
            }
            $sortData = $sortData1;
        }
    }
    return $sortData;
}

function mult_unique($array)
{
    $return = array();
    foreach ($array as $key => $v) {
        if (!in_array($v, $return)) {
            $return[$key] = $v;
        }
    }
    return $return;
}

if (!function_exists('changeArray')) {
    /**
     * @param $arr    查询出来的数组数据
     * @param $field  作为数组键的字段名
     * 转换数组键值
     */
    function changeArray($arr, $field)
    {
        $data = array();
        foreach ($arr as $key => $item) {
            $data[$item[$field]] = $item;
        }
        return $data;
    }
}
/***
 * 生成订单号
 */
if (!function_exists('createOrderNo')) {
    function createOrderNo()
    {
        list($tmp1, $tmp2) = explode(' ', microtime());
        $msec = (int)sprintf('%.0f', (floatval($tmp1) + floatval($tmp2)) * 1000);
        return $msec;
    }
}


if (!function_exists('upload')) {
    /**
     * 图片上传
     *
     * @return \App\Support\Uploads\Upload
     * author zl <178417451@qq.com>
     */
    function upload()
    {
        $upload = new App\Support\Uploads\Upload();
        return $upload;
    }
}

if (!function_exists('articleCategorySelect')) {
    /**
     * 文章分类选择
     *
     * @return \App\Support\Uploads\Upload
     * author zl <178417451@qq.com>
     */
    function articleCategorySelect($id = '')
    {
        $category = new \App\Models\ArticleCategory();
        return $category->caregorySelect($id);
    }
}

if (!function_exists('getSysBasicInfo')) {
    function getSysBasicInfo()
    {
        $info = [];
        $info['sysos'] = $_SERVER["SERVER_SOFTWARE"];      //获取服务器标识的字串
        $info['os'] = PHP_OS;
        $info['sysversion'] = PHP_VERSION;                   //获取PHP服务器版本
        //从服务器中获取GD库的信息
        if (function_exists("gd_info")) {
            $gd = gd_info();
            $info['gdinfo'] = $gd['GD Version'];
        } else {
            $info['gdinfo'] = "未知";
        }
        //从PHP配置文件中获得是否可以远程文件获取
        $info['allowurl'] = ini_get("allow_url_fopen") ? "支持" : "不支持";
        //从PHP配置文件中获得最大上传限制
        $info['max_upload'] = ini_get("file_uploads") ? ini_get("upload_max_filesize") : "Disabled";
        //从PHP配置文件中获得脚本的最大执行时间
        $info['max_ex_time'] = ini_get("max_execution_time") . "秒";
        //以下两条获取服务器时间，中国大陆采用的是东八区的时间,设置时区写成Etc/GMT-8
        date_default_timezone_set("Etc/GMT-8");
        $info['systemtime'] = date("Y-m-d H:i:s", time());
        return $info;
    }

}


function object_array($array)
{
    if (is_object($array)) {
        $array = (array)$array;
    }
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            $array[$key] = object_array($value);
        }
    }
    return $array;
}


/**
 * 后台使用的URL链接函数，强制使用动态传参数模式
 *
 * @param string $controller control文件名
 * @param string $method op方法名
 * @param array $args URL其它参数
 * @param array $type URL模式  1./参数模式   2.?参数模式
 * @return string
 */
function urlAdmin($controller, $method, $args = [], $type = 1)
{
    $controller = ucfirst($controller);
    if ($type == 2) {
        if ($args && is_array($args)) {
            return action("Admin\\{$controller}Controller@$method") . '?' .
            http_build_query($args);
        }
    }
    if ($args && is_array($args)) {
        return action("Admin\\{$controller}Controller@$method", $args);
    }
    return action("Admin\\{$controller}Controller@$method");
}

function urlHome($controller, $method, $args = [], $type = 1)
{
    $controller = ucfirst($controller);
    if ($type == 2) {
        if ($args && is_array($args)) {
            return action("Home\\{$controller}Controller@$method") . '?' .
            http_build_query($args);
        }
    }
    if ($args && is_array($args)) {
        return action("Home\\{$controller}Controller@$method", $args);
    }
    return action("Home\\{$controller}Controller@$method");
}

function ajax_return($data)
{
    return response()->json($data);
}

/**
 * 浏览器友好的变量输出
 * @param mixed $var 变量
 * @param boolean $echo 是否输出 默认为True 如果为false 则返回输出字符串
 * @param string $label 标签 默认为空
 * @param boolean $strict 是否严谨 默认为true
 * @return void|string
 */
function dp($var, $echo = true, $label = null, $strict = true)
{
    $label = ($label === null) ? '' : rtrim($label) . ' ';
    if (!$strict) {
        if (ini_get('html_errors')) {
            $output = print_r($var, true);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        } else {
            $output = $label . print_r($var, true);
        }
    } else {
        ob_start();
        var_dump($var);
        $output = ob_get_clean();
        if (!extension_loaded('xdebug')) {
            $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        }
    }
    if ($echo) {
        echo($output);
        return null;
    } else
        return $output;
}


function getPageNoList($totalPage, $pageNo, $pageSize)
{
    $disPageList = 0;//定义最大链接显示数额
    $disPageList = $pageNo + $pageSize - 1;//最大链接显示数额赋值，公式为"当前页数 + 最大链接显示数额 -1"
    //前页面导航页数
    $pageNoList = array();
    //循环显示出当前页面导航页数
    if ($disPageList <= $totalPage) {
        for ($i = $pageNo; $i <= $disPageList; $i++) {
            $pageNoList[] = $i;
        }
    } else {
        if ($totalPage < $pageSize) {
            for ($i = 1; $i <= $totalPage; $i++) {
                $pageNoList[] = $i;
            }
        } else {
            $start = $totalPage - $pageSize + 1;
            for ($i = $start; $i <= $totalPage; $i++) {
                $pageNoList[] = $i;
            }
        }
    }
    return $pageNoList;
}

function tolog($data, $myfile = '')
{
    is_array($data) ? $str = var_export($data, TRUE) : $str = $data;
    $myfile == '' ? $file = public_path('datalog.txt') : $file = $myfile;
    if ($myfile != '' && !file_exists($myfile)) {
        throw new Exception("Function < tolog > Error : The File Or The FilePath Is Not Exists !");
    }
    file_put_contents($file, $str . "\r\n", FILE_APPEND);
}

function unique_rand($min, $max, $num)
{
    $count = 0;
    $return = array();
    while ($count < $num) {
        $return[] = mt_rand($min, $max);
        $return = array_flip(array_flip($return));
        $count = count($return);
    }
    shuffle($return);
    return $return;
}

/**
 * @param $start_time
 * @param $end_time
 * 获取时间轴
 */
function getX($start_time, $end_time)
{
    $days[] = $start_time;
    while (strtotime($start_time) < strtotime($end_time)) {
        $start_time = date('Y-m-d', strtotime("+1 day $start_time"));
        $days[] = $start_time;
    }
    return $days;
}

/**
 * @param $year  给定的年份
 * @param $month 给定的月份
 * @param $legth 筛选的区间长度 取前六个月就输入6
 * @param int $page 分页
 * @return array
 */
function getLastTimeArea($year, $month, $legth, $page = 1)
{
    if (!$page) {
        $page = 1;
    }
    $monthNum = $month + $legth - $page * $legth;
    $num = 1;
    if ($monthNum < -12) {
        $num = ceil($monthNum / (-12));
    }
    $timeAreaList = [];
    for ($i = 0; $i < $legth; $i++) {
        $temMonth = $monthNum - $i;
        $temYear = $year;
        if ($temMonth <= 0) {
            $temYear = $year - $num;
            $temMonth = $temMonth + 12 * $num;
            if ($temMonth <= 0) {
                $temMonth += 12;
                $temYear -= 1;
            }
        }
        $startMonth = strtotime($temYear . '/' . $temMonth . '/01');//该月的月初时间戳
        $endMonth = strtotime($temYear . '/' . ($temMonth + 1) . '/01') - 1;//该月的月末时间戳
        $res['date'] = $temYear . '年' . $temMonth . '月'; //该月的月初格式化时间
        $res['startMonth'] = $temYear . '/' . $temMonth . '/01'; //该月的月初格式化时间
        $res['endMonth'] = date('Y/m/d', $endMonth);//该月的月末格式化时间
        $res['timeArea'] = implode(',', [$startMonth, $endMonth]);//区间时间戳
        $timeAreaList[] = $res;
    }
    return $timeAreaList;
}

/**
 *上传多图  仅限 base64
 * @param $imgs
 * @param bool|false $dir 路径
 * @param bool|true $isdel
 * @return string
 */
function upImgs($imgs, $dir = false)
{
    $dir = $dir ? $dir : date('Ymd');
    $res = [];
    foreach ($imgs as $k => $v) {
        if (file_exists($v)) {
            $res[$k] = $v;
        } else {
            $v = explode(',', $v);
            $imgpath = $dir . "/";
            preg_match('/image\/(.*);base64/u', $v[0], $imgtype);
            $imgtype = $imgtype[1] == "jpeg" ? 'jpg' : $imgtype[1];
            if (!file_exists($imgpath)) {
                mkdir($imgpath);
            }
            list($usec, $sec) = explode(" ", microtime());
            $imgname = $sec . str_replace('0.', '_', $usec);
            $imgname = $imgname . '.' . $imgtype;
            $base64 = base64_decode(end($v));
            $save = file_put_contents($imgpath . $imgname, $base64);
            if ($save) {
                $res[$k] = $imgpath . $imgname;
            }
        }
    }
    return $res;
}


/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0, $adv = false)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) return $ip[$type];
    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) unset($arr[$pos]);
            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

function addSession($key, $value)
{
    session([$key => $value]);
}

/**
 * 把图片转成base64
 * @param $image_file
 * @return string
 */
function base64EncodeImage ($image_file) {
    $base64_image = '';
    $image_info = getimagesize($image_file);
    $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
    $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
    return $base64_image;
}

/**
 * 异或位加函数
 * @param  [type]  $value 要加解密的字符串
 * @param  integer $key   盐
 * @return [type]
 */
function xorencrypt( $str, $key ){
    $slen = strlen( $str );
    $klen = strlen( $key );
    $cipher = '';
    for ($i=0;$i<$slen;$i=$i+$klen) {
        $cipher .= substr( $str, $i, $klen )^$key;
    }
    return $cipher;
}

function get_rand($proArr) {
    $result = '';

    //概率数组的总概率精度
    $proSum = array_sum($proArr);

    //概率数组循环
    foreach ($proArr as $key => $proCur) {
        $randNum = mt_rand(1, $proSum);
        if ($randNum <= $proCur) {
            $result = $key;
            break;
        } else {
            $proSum -= $proCur;
        }
    }
    unset ($proArr);

    return $result;
}

/**
 * 二维数组根据字段进行排序
 * @params array $array 需要排序的数组
 * @params string $field 排序的字段
 * @params string $sort 排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
 */
function arraySequence($array, $field, $sort = 'SORT_DESC')
{
    $arrSort = array();
    foreach ($array as $uniqid => $row) {
        foreach ($row as $key => $value) {
            $arrSort[$key][$uniqid] = $value;
        }
    }
    array_multisort($arrSort[$field], constant($sort), $array);
    return $array;
}

/**
 * 时间格式化
 */
function timeFormat($second){
    $h = intval($second/(60*60));
    $remain = intval($h%(60*60));
    $m = intval($remain/60);
    $remain = intval($remain%60);
    $s = $remain;
    return $h.":".$m.":".$s;
}

/**
 * 截取文件后缀名
 * @param $file
 */
function get_extension($file)
{
   return substr(strrchr($file, '.'), 1);
}

/**
 * *
 *等比缩放
 * @param unknown_type $srcImage   源图片路径
 * @param unknown_type $toFile     目标图片路径
 * @param unknown_type $maxWidth   最大宽
 * @param unknown_type $maxHeight  最大高
 * @param unknown_type $imgQuality 图片质量
 * @return unknown
 */
function resize($srcImage,$toFile,$maxWidth = 100,$maxHeight = 100,$imgQuality=100)
{
    list($width, $height, $type, $attr) = getimagesize($srcImage);
    if($width < $maxWidth  || $height < $maxHeight) return ;
    switch ($type) {
        case 1: $img = imagecreatefromgif($srcImage); break;
        case 2: $img = imagecreatefromjpeg($srcImage); break;
        case 3: $img = imagecreatefrompng($srcImage); break;
    }
    $scale = min($maxWidth/$width, $maxHeight/$height); //求出绽放比例

    if($scale < 1) {
        $newWidth = floor($scale*$width);
        $newHeight = floor($scale*$height);
        $newImg = imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($newImg, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
        $newName = "";
        $toFile = preg_replace("/(.gif|.jpg|.jpeg|.png)/i","",$toFile);
        switch($type) {
            case 1: if(imagegif($newImg, "$toFile$newName.gif", $imgQuality))
                return "$newName.gif"; break;
            case 2: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality))
                return "$newName.jpg"; break;
            case 3: if(imagepng($newImg, "$toFile$newName.png", $imgQuality))
                return "$newName.png"; break;
            default: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality))
                return "$newName.jpg"; break;
        }
        imagedestroy($newImg);
    }
    imagedestroy($img);
    return false;
}
?>
